<?php

namespace app\index\service;

use app\common\model\SourceCollect;
use app\index\dao\SourceCollectDao;
use app\index\model\UM as UM;
use ary\Ary;
use think\exception\ValidateException;

/**
 * Class SourceCollectService
 * @package app\index\service
 */
class SourceCollectService
{
    // dao
    private SourceCollectDao $sourceCollectDao;

    public function __construct(SourceCollectDao $sourceCollectDao)
    {
        $this->sourceCollectDao = $sourceCollectDao;
    }

    /**
     * 添加收藏
     * @param UM $user
     * @param $id
     * @return void
     */
    public function add(UM $user, $id): void
    {
        $memberId = $user->id;

        $sourceResponse = $this->getAry()->getSourceDetail(['source_id' => $id]);

        $decodeContents = $sourceResponse->getDecodeContentsOrThrow('找不到该线索或已被删除');

        $source = $decodeContents['data'];

        if (!is_array($source) || empty($source)) {
            throw new ValidateException('找不到该线索或已被删除');
        }

        $params = [
            'memberId' => $memberId,
            'sourceId' => $id,
        ];

        $this->sourceCollectDao->replaceActive($params, []);
    }

    /**
     * 删除
     * @param UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        $memberId = $user->id;

        $record = SourceCollect::field(true)
            ->where('memberId', $memberId)
            ->where('sourceId', $id)
            ->find();

        if (is_null($record)) {
            return;
        }

        $this->sourceCollectDao->deleteModel($record);
    }

    private function getAry(): Ary
    {
        return app(Ary::class);
    }
}
